<template>
  <div ref="previewWrapper" class="flow-preview">

  </div>
  {{ rendered() }}
</template>
<script setup>
import './flow-style.css'
import {createProps} from '@/utils';
import {shallowRef} from 'vue';
import FlowSupport from '@comp/FlowPreview/FlowSupport';

defineOptions({name: 'FlowPreview'});
const props = defineProps({
  flow: createProps(Object)
});
const previewWrapper = shallowRef();
const graph = shallowRef();

function rendered() {
  if (previewWrapper.value && props.flow) {
    graph.value = graph.value || FlowSupport.createGraph(previewWrapper.value, getFlowModel());
    reRender();
  } else {
    graph.value = undefined;
  }

  cancelResizeListener()
  addResizeListener()
}

function addResizeListener() {
  try {
    window.FlowPreviewObserver =  new ResizeObserver(entries => {
      try {
        reRender();
      } catch (e) {
      }
    });
    window.FlowPreviewObserver.observe(previewWrapper.value);
  } catch (e) {
  }
}

function cancelResizeListener() {
  try {
    window.FlowPreviewObserver.disconnect();
  } catch(e) {
  }
}

function getFlowModel() {
  let model = props.flow.model;
  return JSON.parse(model);
}

function reRender() {
  graph.value.reRender();
}
</script>
<style scoped lang="less">
.flow-preview {
  width: 100%;
  height: 100%;
}
</style>